import time

import uvicorn
from fastapi import FastAPI,Request
from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles
from tortoise.contrib.fastapi import register_tortoise

from settings import TORTOISE_ORM

from api.student import router

app = FastAPI()

register_tortoise(
    app,
    config=TORTOISE_ORM,
    # generate_schemas=True,  # 如果数据库为空，则自动生成对应表单，生产环境不要开
    # add_exception_handlers=True, # 生产环境不要开，会泄露调试信息
)

app.mount("/static", StaticFiles(directory="static"), name="static")

app.include_router(router=router, prefix="/api/student", tags=["学生管理"])



# 全局处理跨域
# @app.middleware("http")
# async def MyCORSMiddleware(request: Request, call_next):
#     response = await call_next(request)
#     response.headers["Access-Control-Allow-Origin"] = "*"
#     return response

# 使用系统的跨域函数
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 明确类型: List[str]
    allow_methods=["*"],  # 明确类型: List[str]
    allow_headers=["*"],  # 明确类型: List[str]
    allow_credentials=True,  # 是否允许凭据（新增必填项）
    expose_headers=[],  # 暴露的响应头（默认空列表）
    max_age=600  # 预检请求缓存时间（秒）
)



# 定义中间件（多个中间件从下往上执行）
@app.middleware("http")
async def m2(request: Request, call_next):
    # 请求代码块
    print("m2 request")
    response = await call_next(request)
    # 响应代码块
    # 自定义处理
    response.headers["author"] = "Jungle"
    print("m2 response")

    return response




@app.middleware("http")
async def m1(request: Request, call_next):
    # 请求代码块
    print("m1 request")
    # ip处理
    # if request.client.host in ["127.0.0.1"]: # 黑名单
    #     return Response(status_code=403,content="visit forbidden")
    print(f"访问的路径: {request.method} {request.url.path}")

    # if request.url.path in ["/user/get"]:
    #     return Response(status_code=403, content="visit forbidden")

    start = time.time()
    response = await call_next(request)
    # 响应代码块
    print("m1 response")
    end = time.time()
    response.headers["time"] = str(end - start)
    return response







if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8000,reload=True)
